
<!DOCTYPE HTML>
<html>
<head>
    <title>Flask-SocketIO Test</title>
    <script src="./js/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <script src="./js/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>

        <script type="text/javascript" charset="utf-8">
            function guid() {
                return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0,
                        v = c == 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });
            }
    
            var uid = guid();
            /*
            * 001 狮王争霸
            * */
            var aid = "001";
    
    
            function prepareSendData(text)
            {
                return {
    
                    aid : aid,
                    uid: uid,
                    data: text
                }
            }
    
            $(document).ready(function() {
                // Use a "/test" namespace.
                // An application can open a connection on multiple namespaces, and
                // Socket.IO will multiplex all those connections on a single
                // physical channel. If you don't care about multiple channels, you
                // can set the namespace to an empty string.
                namespace = '/socket.io.v1';
    
                // Connect to the Socket.IO server.
                // The connection URL has the following format, relative to the current page:
                //     http[s]://<domain>:<port>[/<namespace>]
                
    
    
                /*
                ...
                connect
    
                options = {
                        port: 80
                      , secure: false
                      , document: 'document' in global ? document : false
                      , resource: 'socket.io'
                      , transports: io.transports
                      , 'connect timeout': 10000
                      , 'try multiple transports': true
                      , 'reconnect': true
                      , 'reconnection delay': 500
                      , 'reconnection limit': Infinity
                      , 'reopen delay': 3000
                      , 'max reconnection attempts': 10
                      , 'sync disconnect on unload': false
                      , 'auto connect': true
                      , 'flash policy port': 10843
                      , 'manualFlush': false
                    };
                ...
    
                connect timeout
                默认值： 5002
    
                作用：设置创建连接所接收的超时时间，单位是毫秒。
    
                try multiple transports
                默认值： true
    
                作用：当连接超时后是否允许Socket.io以其他连接方式尝试连接
    
                reconnect
                默认值： true
    
                作用：当连接终止后，是否允许Socket.io自动进行重连
    
                reconnection delay
                默认值： 500
    
                作用：为Socket.io的重连设置一个时间间隔，内部会在多次重连尝试时采用该值的指数值间隔，用来避免性能损耗（500 > 1000 > 2000 > 4000 > 8000）
    
                max reconnection attempts
                默认值： 10
    
                作用：设置一个重连的最大尝试次数，超过这个值后Socket.io会使用所有允许的其他连接方式尝试重连，直到最终失败。
    
                transports
                默认值： ['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling']
    
                作用：默认支持的链接方式（顺序敏感）
                */
    
                // version 2.2.0
                // https://github.com/socketio/socket.io-client/
    
                var token = $('#token').val();
                var url = location.protocol + '//' + document.domain + ':' + location.port + namespace;
                url = "http://192.168.3.41:5002" + namespace;
                
    
                url += "?uid="+uid + "&aid="+aid; // 加上参数
                url += "&token=" + token;
                var socket = io.connect(url);
    
                //var socket = io(namespace);
    
                // Event handler for new connections.
                // The callback function is invoked when a connection with the
                // server is established.
    
    
                socket.on('connect', function() {
                    var data = prepareSendData('I\'m connected!')
                    socket.emit('client_send_message', data);
                });
    
                socket.on('connect_error', function (error) {
                    console.log("connect_error : " + error)
                    $('#log').append('<br>' + $('<div/>').text(error).html());
                })
    
                socket.on('connect_timeout', (timeout) => {
                  // ...
                });
    
                console.log("socket : " + socket)
    
    
                socket.on('error', function (msg) {
                    console.log("error : " + msg)
                    $('#log').append('<br>' + $('<div/>').text("error : " + msg).html());
                })
    
                socket.on('disconnect', function (event) {
                    console.log('disconnect :' +event )
                })
    
    
                // Event handler for server sent data.
                // The callback function is invoked whenever the server emits data
                // to the client. The data is then displayed in the "Received"
                // section of the page.
                socket.on('server_response', function(msg, cb) {
                    var text = 'Received #' + JSON.stringify(msg)
    
                    $('#log').append('<br>' + $('<div/>').text(text).html());
                    if (cb) cb();
                });
    
                // Interval function that tests message latency by sending a "ping"
                // message. The server then responds with a "pong" message and the
                // round trip time is measured.
                var ping_pong_times = [];
                var start_time;
                window.setInterval(function() {
                    start_time = (new Date).getTime();
                    var data = prepareSendData('')
    
                    socket.emit('client_ping_pong', data);
                }, 1000);
    
                // Handler for the "pong" message. When the pong is received, the
                // time from the ping is stored, and the average of the last 30
                // samples is average and displayed.
                socket.on('server_pong', function() {
                    var latency = (new Date).getTime() - start_time;
                    ping_pong_times.push(latency);
                    ping_pong_times = ping_pong_times.slice(-30); // keep last 30 samples
                    var sum = 0;
                    for (var i = 0; i < ping_pong_times.length; i++)
                        sum += ping_pong_times[i];
                    $('#ping-pong').text(Math.round(10 * sum / ping_pong_times.length) / 10);
                });
    
                // Handlers for the different forms in the page.
                // These accept data from the user and send it to the server in a
                // variety of ways
                $('form#emit').submit(function(event) {
                    var data = prepareSendData($('#emit_data').val());
    
                    socket.emit('client_send_message', data);
                    return false;
                });
                $('form#broadcast').submit(function(event) {
                    var data = prepareSendData($('#broadcast_data').val());
    
                    socket.emit('client_broadcast_message', data);
                    return false;
                });
                $('form#join').submit(function(event) {
                    var data = prepareSendData('');
                    data.room = $('#join_room').val();
    
                    socket.emit('join', data);
                    return false;
                });
                $('form#leave').submit(function(event) {
                    var data = prepareSendData('');
                    data.room = $('#leave_room').val();
    
                    socket.emit('leave', data);
                    return false;
                });
                $('form#send_room').submit(function(event) {
                    var data = prepareSendData($('#room_data').val());
                    data.room = $('#room_name').val();
    
                    socket.emit('client_send_room_message', data);
                    return false;
                });
                $('form#close').submit(function(event) {
                    var data = prepareSendData('');
                    data.room = $('#close_room').val();
    
                    socket.emit('close_room', data);
                    return false;
                });
                $('form#disconnect').submit(function(event) {
                    var data = prepareSendData('')
                    socket.emit('disconnect_request', data);
                    return false;
                });
    
                $('#uid').text(uid);
            });
        </script>
    </head>
    <body>
        <h1>Flask-SocketIO Test</h1>
        <p>Async mode is: <b>eventlet</b>, uid : <span id="uid"></span></p>
        <p>Average ping/pong latency: <b><span id="ping-pong"></span>ms</b></p>
    
    
        <h2>Token:<br/>
            <textarea type="text"  placeholder="token"
                      style="width: 600px;height: 200px"
                      name="token"
                      id="token">JWT eyJhbGciOiJIUzUxMiIsImlhdCI6MTU5OTAyMjkzMCwiZXhwIjoxNTk5MTk1NzMwfQ.eyJhaWQiOiIxMjMiLCJzaWQiOiJiIiwidWlkIjoiMTU1YWU1NDgtZTA4Yy00ZjhmLWExZDAtODllNjcwMGNmY2ViIiwicGxhdGZvcm0iOjAsImNyZWF0ZV9hdCI6IjIwMjAtMDktMDIgMTM6MDI6MTAiLCJleHBpcmVfaW4iOjE3MjgwMH0.S9HNLkSErhU4EyJL6NXMJrgrrI01GGS0fuPWAgm6E_oUQ3xOL4oARwc0psJsD48QtLXjr_MyxV3RAzMBpAqSDw</textarea>
        </h2>
    
        <h2>Send:</h2>
        <form id="emit" method="POST" action='#'>
            <input type="text" name="emit_data" id="emit_data" placeholder="Message">
            <input type="submit" value="Echo">
        </form>
        <form id="broadcast" method="POST" action='#'>
            <input type="text" name="broadcast_data" id="broadcast_data" placeholder="Message">
            <input type="submit" value="Broadcast">
        </form>
        <form id="join" method="POST" action='#'>
            <input type="text" name="join_room" id="join_room" placeholder="Room Name">
            <input type="submit" value="Join Room">
        </form>
        <form id="leave" method="POST" action='#'>
            <input type="text" name="leave_room" id="leave_room" placeholder="Room Name">
            <input type="submit" value="Leave Room">
        </form>
        <form id="send_room" method="POST" action='#'>
            <input type="text" name="room_name" id="room_name" placeholder="Room Name">
            <input type="text" name="room_data" id="room_data" placeholder="Message">
            <input type="submit" value="Send to Room">
        </form>
        <form id="close" method="POST" action="#">
            <input type="text" name="close_room" id="close_room" placeholder="Room Name">
            <input type="submit" value="Close Room">
        </form>
        <form id="disconnect" method="POST" action="#">
            <input type="submit" value="Disconnect">
        </form>
        <h2>Receive:</h2>
        <div id="log"></div>
    </body>
    </html>